//
//  HWGameWebView.m
//  94hwanGame
//
//  Created by 王治庭 on 2019/3/21.
//  Copyright © 2019 王治庭. All rights reserved.
//

#import "HWGameWebView.h"
#import <WebKit/WebKit.h>
#import "UIColor+Hex.h"
#import "HWHeaderView.h"
#import <JavaScriptCore/JavaScriptCore.h>
//#import "HWFirstDetailViewController.h"
#import "HWWebViewGameViewController.h"

@interface HWGameWebView()<WKUIDelegate,WKNavigationDelegate, WKScriptMessageHandler>

@end

@implementation HWGameWebView
{
   //  WKWebView *_webView;
    NSString *_urlString;
    HWHeaderView *headerView;
    UILabel *title;
    UIButton *backButton;
}

+ (instancetype)initWithUrlString:(NSString *)urlString {
    return [[HWGameWebView alloc] initWithUrlString:urlString];
}

- (instancetype)initWithFrame:(CGRect)frame urlString:(NSString *)urlString {
    _urlString = urlString;
    return [self initWithFrame:frame];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        
       // 全部评论
        
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = [[WKUserContentController alloc] init];
        [configuration.userContentController addScriptMessageHandler:self name:@"gameinfo"];
        
       
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [request setHTTPMethod:@"GET"];
        [_webView loadRequest:request];
        //
        [self addSubview:_webView];
//        [self webViewDidFinishload:_webView];
        
        [_webView reload];
        
        [_webView  addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
        
        [_webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
        
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    [super layoutSubviews];
    
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mas_top);
        make.left.mas_equalTo(self.mas_left);
        make.bottom.mas_equalTo(self.mas_bottom);
        make.right.mas_equalTo(self.mas_right);
    }];
    
}





- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0){
         [webView reload];
}


- (instancetype)initWithUrlString:(NSString *)urlString {
    _urlString = urlString;
    return [self initWithFrame:CGRectZero];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"gameinfo"]) {
        //调用原生扫码
        NSLog(@"返回的数据在这里%@", message.body);
//        HWFirstDetailViewController *detail = [[HWFirstDetailViewController alloc] init];
//        detail.gid = message.body;
//        [[HWViewUtils getCurrentVC].navigationController pushViewController:detail animated:YES];
    }
}


//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    if ([keyPath isEqualToString:@"title"]){
//        if (object == _webView) {
//            title.text = _webView.title;
//        }else{
//            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//        }
//    }
//}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"title"]){
        if (object == _webView) {
            title.text = self->_webView.title;
            self.kongzhiView.navigationItem.title = _webView.title;
            
            
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}






- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
    }
    NSURL *url = navigationAction.request.URL;
    if ([url.absoluteString containsString:@"alipay"] || [url.absoluteString containsString:@"weixin"]) {
        if (url.scheme != nil) {
//            if ([url.scheme  isEqual: @"weixin"]) {
//                NSLog(@"微信支付");
//                [self catchEvent:url];
//                decisionHandler(WKNavigationActionPolicyAllow);
//                return;
//            } else if ([url.scheme isEqualToString:@"alipay"]) {
//                NSLog(@"支付宝支付");
                [self catchEvent:url];
                decisionHandler(WKNavigationActionPolicyAllow);
                return;
//            }
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)catchEvent:(NSURL *)eventUrl {
    if ([eventUrl.host isEqualToString:@"wap"] || [eventUrl.host isEqualToString:@"alipayclient"]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:eventUrl options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:eventUrl];
        }
    } else {
        [[UIApplication sharedApplication] openURL:eventUrl options:@{} completionHandler:nil];
    }
}


-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
//
//    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//        completionHandler();
//
//    }])];

    // [self presentViewController:alertController animated:YES completion:nil];

    if([message isEqualToString:@"支付成功"]){


        NSLog(@"%@", message);
//         self.ReturnValueBlock(self.idstr);
//
//        [self  dismissViewControllerAnimated:YES completion:^{
//
//        }];
//
        
        completionHandler();


    } else if([message isEqualToString:@"领取代金券"]){

         NSLog(@" %@", message);

          completionHandler();
        
        

    } else if ([message isEqualToString:@"注销成功"]) {
        [MBProgressHUD showError:@"注销成功"];
        [HWLocallyStoredData setUserID:@""];
        [HWUniversal.getCurrentVc.navigationController popToRootViewControllerAnimated:YES];
//        [[UIApplication sharedApplication].keyWindow.rootViewController.navigationController popToRootViewControllerAnimated:YES];
        completionHandler();
    } else {

         
         [MBProgressHUD showError:message];
        
        
          completionHandler();



    }









}




//- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0){
//       [webView reload];
//
//}
//
//
//// 页面开始加载时调用
//- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
//    
//    
//}
//  // 页面加载失败时调用
//- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
//   // [self.progressView setProgress:0.0f animated:NO];
//    
//    NSLog(@"%@",error);
//    
//    
//    if (error != nil) {
//        [self deleteWebCookiesCache];
//        
//    }
//    
//    NSLog(@"%@",error);
//    
//    
//    
//}
//
//
//
//- (void)deleteWebCookiesCache {
//    
//    
//// https://blog.csdn.net/u013602835/article/details/81171571
//        
//        if (@available(iOS 9.0, *)) {//iOS9及以上
//            WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
//            [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
//                             completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
//                                 for (WKWebsiteDataRecord *record in records)
//                                 {
//                                     //if ( [record.displayName containsString:@"baidu"]) //取消备注，可以针对某域名做专门的清除，否则是全部清除
//                                     //               {
//                                     [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes
//                                                                               forDataRecords:@[record]
//                                                                            completionHandler:^{
//                                                                                NSLog(@"Cookies for %@ deleted successfully",record.displayName);
//                                                                            }];
//                                     //               }
//                                 }
//                             }];
//    }else { //iOS9以下
//        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
//        NSError *errors;
//        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
//    }
//    
//    
//    
//    [_webView reload];
//
//
//}
//






@end

